#!/usr/bin/env python2
#-*- coding: utf-8 -*-


import os
import re
import json
import time
import sys
import cgi
import web
import uuid
import httplib2
import httplib
import traceback
import subprocess
import datetime


from Umpweb.db import api as db_api
from Umpweb.common import utils
from Umpweb.base import render_jinja


urls = (
        '/list',            'AlertList',
        '/grid',            'GridAlert',
        '/handler',         'HandlerAlert',
        '/count',           'AlertCount',

)


app = web.application(urls, locals())
render = render_jinja('static/templates/alert', encoding='utf-8',)


class AlertList:
    def GET(self):
        return render.alert_list()


class GridAlert:

    def GET(self):
        web_input = web.input()
        page, total, records, rows = \
                utils.grid_rows_query(db_api.alert_table, web_input, filters={})
        cells = ['id', 'returncode', 'detail', 'level', 'position', 'obj', 'is_handled','is_handled', 'created_at','option']
        rows_json = utils.grid_json(page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json


class HandlerAlert:
    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        ids = x.get('ids')
        values = {
            'ids': ids,
        }
        body = {'AlertHandler':{'params':values}}
        try:
            reply = web.config._server.api_sync_call(body)
        except Exception, err:
            traceback.print_exc()
            return utils.exception2json(e)
        return reply

class AlertCount():

    def GET(self):
        web.header("Content-Type", "text/plain")
        warning_num = db_api.alert_count_nothandled()
        return warning_num
